package com.iwith.dongmoon.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iwith.dongmoon.gsonlist.BoardList;
import com.iwith.dongmoon.util.ApiCode;
import com.iwith.dongmoon.util.HttpRequestor;
import com.iwith.dongmoon.util.ResultCode;
import com.iwith.dongmoon.util.ThreadInterface;
import com.iwith.dongmoon.util.ThreadTask;

public class WriteActivity extends Activity implements OnClickListener{
	public static final int REQUEST_GALLERY = 1;
	public static final int REQUEST_CAMERA = 0;
	
	private EditText subject;
	private EditText content;
	private Button btn_image;
	private Button btn_write;
	private Button btn_cancel;

	private String imagePath="no image";

	private String boardname;
	private String userid;
	private String code;
	
	private Context mContext;
	
	private File imageFile;
	
	private AlertDialog.Builder mAlertDialog;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.write);

		Initialize();
	}
	
	private void Initialize(){
		mContext=this;
		boardname = getIntent().getExtras().getString("boardname");
		code = getIntent().getExtras().getString("code");
		userid=getIntent().getExtras().getString("userid");
		
		subject = (EditText) findViewById(R.id.write_subject);
		content = (EditText) findViewById(R.id.write_content);
		btn_image = (Button) findViewById(R.id.write_imagepath);
		btn_write = (Button) findViewById(R.id.write_updatebt);
		btn_cancel = (Button) findViewById(R.id.write_cancelbt);
		mAlertDialog = new AlertDialog.Builder(this);
		
		btn_write.setOnClickListener(this);
		btn_image.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		ThreadTask.onFinishAll();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		ThreadTask.onFinishAll();
	}
	
	private void writeContent(){
		ThreadInterface threadInterface = new ThreadInterface(){
			BoardList boardList;
			public void onThread() {
				Gson gson = new Gson();
				HttpRequestor data = null;
				try {
					String api = null;
					if (code.equals(ApiCode.BULLETINS) == true) {
						api = ApiCode.API_BULLETIN+"/insert";
					} else if (code.equals(ApiCode.NEWS) == true) {
						api = ApiCode.API_NEWS+"/insert";
					}
					data = new HttpRequestor(new URL(getString(R.string.api_url) + api));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}

				if (data != null) {
					data.addParameter("userid", userid);
					data.addParameter("subject", subject.getText().toString());
					data.addParameter("content", content.getText().toString());
					data.addParameter("datetime", DateFormat.format("yyyy-MM-dd kk:mm:ss", new Date()).toString());
					data.addFile("picture", imageFile);
					try {
						InputStream is = data.sendMultipartPost((Activity) mContext);
						BufferedReader bin = new BufferedReader(new InputStreamReader(is));
						String line = bin.readLine();
						boardList = gson.fromJson(line, BoardList.class);
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
					}
				}
			}
			public void onThreadEnd() {
				if(boardList!=null){
					if(boardList.getResultCode().equals(ResultCode.SUCCESS)==true){
						Toast.makeText(mContext, "Writing News is Success", Toast.LENGTH_LONG).show();
						/*try{
							mContext.wait(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						} finally {
						}*/
						finish();
					}
				}
				
			}
		};
		ThreadTask task = new ThreadTask((Activity)mContext, threadInterface);
		task.execute();
	}
	


	public void alertToast(String message) {
		Toast alertMessage = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		alertMessage.show();
	}

	
	@TargetApi(8)
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;

		if (requestCode == REQUEST_GALLERY) {
			Uri imageUri = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String filePath = cursor.getString(columnIndex);
			cursor.close();

			Bitmap bitmap = BitmapFactory.decodeFile(filePath);// , option);

			// 이미지 생성
			File imageFile = new File(filePath);

			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			this.imageFile=imageFile;
			//uploadPicture(imageFile, thumbnailFile);

		} else if (requestCode == REQUEST_CAMERA) {
			// intent 의 여분 데이터로 저장된 비트맵 이미지를 얻는다. Bitmap bitmap = (Bitmap)
			Bitmap bitmap = (Bitmap) data.getExtras().get("data");

			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			File imageFile = new File(path, "iwith_image_" + userid + ".jpg");

			FileOutputStream imageOut = null;
			try {
				imageOut = new FileOutputStream(imageFile.getPath());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (imageOut != null) {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOut);
			}

			this.imageFile=imageFile;
			//uploadPicture(imageFile, thumbnailFile);
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==btn_write.getId()){
			if (subject.getText().length() == 0) {
				alertToast("제목을 입력해주세요");
				return;
			} else if (content.getText().length() == 0) {
				alertToast("내용을 입력해주세요");
				return;
			}
			
			writeContent();
		} else if(v.getId()==btn_cancel.getId()){
			finish();
		} else if(v.getId()==btn_image.getId()){
			final String items[] = { "앨범에서 불러오기", "찍어서 올리기", "취소" };
			mAlertDialog.setTitle("사진등록하기");
			mAlertDialog.setSingleChoiceItems(items, 0,	new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent intent = null;
					switch (whichButton) {
					case 0:
						intent = new Intent(Intent.ACTION_PICK);
						intent.setType("image/*");
						startActivityForResult(intent, REQUEST_GALLERY);
						break;

					case 1:
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(intent, REQUEST_CAMERA);
						break;
					}
					dialog.dismiss();
				}
			});
			mAlertDialog.show();
		}
	}
}
